import { _decorator, Component, Node, Prefab, director, find, Label, Sprite, SpriteFrame, instantiate, assetManager, Texture2D, UITransform } from 'cc';
import { ImageAsset } from 'cc';
import { userRankInfo } from './rankInfo'
import api from '../api'
const { ccclass, property } = _decorator;


interface rankingItem {
  id: number;
  nickname: string;
  headUrl: string;
  rank: number;
  rankName: any;
  totalScore: number;
  ranking: number;
  maxScore: number;
}

interface UserRankInfo {
  dailyRankingList: rankingItem[];
  totalRankingList: rankingItem[];
  myDailyRanking: rankingItem;
  myTotalRanking: rankingItem;
}
@ccclass('rankingMgr')
export class rankingMgr extends Component {
  @property({ type: Node })
  public goBack: Node | null = null; // 返回

  @property({ type: Node })
  public menuLeft: Node | null = null; // menuLeft

  @property({ type: Node })
  public menuRight: Node | null = null; // menuRight

  @property({ type: [Node] })
  public menuLeftList: Node[] = []; // menuLeft

  @property({ type: [Node] })
  public menuRightList: Node[] = []; // menuRight

  @property({ type: Node })
  public totalRankingRef: Node | null = null; // totalRanking

  @property({ type: Node })
  public dailyRankingRef: Node | null = null; // dailyRanking

  @property({ type: Prefab })
  public item: Prefab | null = null; // item  scroll-item-Prefab

  @property({ type: [SpriteFrame] })
  public guanzhiList: SpriteFrame[] = []

  @property({ type: [SpriteFrame] })
  public itemLeftList: SpriteFrame[] = []

  private totalScrollViewRef: Node | null = null;
  private dailyScrollViewRef: Node | null = null;
  private totalMyRankingRef: Node | null = null;
  private dailyMyRankingRef: Node | null = null;

  private userRankInfo: UserRankInfo = userRankInfo
  private menuType = 2
  private imglist = [] // 官职列表


  async start() {
    this.totalScrollViewRef = find("Canvas/totalRanking/ScrollView/view/content")
    this.dailyScrollViewRef = find("Canvas/dailyRanking/ScrollView/view/content")
    this.totalMyRankingRef = find("Canvas/totalRanking/my-ranking")
    this.dailyMyRankingRef = find("Canvas/dailyRanking/my-ranking")
    // console.log(this.totalScrollViewRef, 'this.totalScrollViewRef')
    this.menuLeft.on(Node.EventType.TOUCH_START, this.changeMenuLeft, this);
    this.menuRight.on(Node.EventType.TOUCH_START, this.changeMenuRight, this);
    this.goBack.on(Node.EventType.TOUCH_START, this.goBackHome, this);
    
    await this.init()
  }

  update(deltaTime: number) {

  }

  async init() {
    await this.getValidTextbookLabelInfo()
    await this.getUserRankInfo()
    this.handleTotalRanking()
    this.handleDailyRanking()
    this.changeMenu()
  }

  goBackHome() {
    director.loadScene('home')
  }

  // 切换menuType
  changeMenu() {
    switch (this.menuType) {
      case 1:
        this.changeMenuLeft()
        break;
      default:
        this.changeMenuRight()
        break;
    }
  }

  changeMenuLeft() {
    // console.log('zuo')
    this.menuType = 1
    this.totalRankingRef.active = false
    this.dailyRankingRef.active = true
    this.menuLeftList[0].active = true
    this.menuLeftList[1].active = false
    this.menuRightList[0].active = false
    this.menuRightList[1].active = true
  }

  changeMenuRight() {
    // console.log('you')
    this.menuType = 2
    this.dailyRankingRef.active = false
    this.totalRankingRef.active = true
    this.menuLeftList[0].active = false
    this.menuLeftList[1].active = true
    this.menuRightList[0].active = true
    this.menuRightList[1].active = false
  }

  // 获取排行榜
  async getUserRankInfo() {
    await api.game.getUserRankInfo().then((res: UserRankInfo) => {
      this.userRankInfo = res ? res : this.userRankInfo
      console.log('res', this.userRankInfo)
    })
  }

  // 获取官职体系
  async getValidTextbookLabelInfo() {
    await api.game.getByKey({
      key: 'littleGameAchievement'
    }).then((res) => {
      this.imglist = res.list
      console.log(11111, 'imglist')
    })
  }

  // 24小时榜
  handleDailyRanking() {
    this.handledailyRankingRef()
    // console.log(this.userRankInfo.myDailyRanking.ranking, 'this.userRankInfo.myDailyRanking.ranking')
    if (this.userRankInfo.myDailyRanking.totalScore > 0) {
      this.dailyMyRankingRef.active = true
      this.prefabRendering(this.dailyMyRankingRef, this.userRankInfo.myDailyRanking, this.userRankInfo.myDailyRanking.ranking)
    } else {
      this.dailyMyRankingRef.active = false
    }
  }

  // 总分榜
  handleTotalRanking() {
    this.handleTotalRankingRef()
    if (this.userRankInfo.myTotalRanking.totalScore > 0) {
      this.totalMyRankingRef.active = true
      this.prefabRendering(this.totalMyRankingRef, this.userRankInfo.myTotalRanking, this.userRankInfo.myTotalRanking.ranking)
    } else {
      this.totalMyRankingRef.active = false
    }
  }


  // 24小时榜scrollView
  handledailyRankingRef() {
    this.dailyScrollViewRef.getComponent(UITransform).height = this.userRankInfo.dailyRankingList.length * 130
    this.userRankInfo.dailyRankingList.forEach((item, index) => {
      // console.log(item)
      let itemRef = instantiate(this.item);
      const prefab = this.prefabRendering(itemRef, item, index + 1)
      this.dailyScrollViewRef.addChild(prefab)
    });
  }

  // 总分榜排行scrollView
  handleTotalRankingRef() {
    this.totalScrollViewRef.getComponent(UITransform).height = this.userRankInfo.totalRankingList.length * 130
    this.userRankInfo.totalRankingList.forEach((item, index) => {
      // console.log(item)
      let itemRef = instantiate(this.item);
      const prefab = this.prefabRendering(itemRef, item, index + 1)
      this.totalScrollViewRef.addChild(prefab)
    });
  }

  // 更新预制体ui
  prefabRendering(prefab, item, index) {
    // console.log(prefab.getChildByName('info'), 'info')
    if (index && index < 4) {
      this.handleItemLeft(prefab, index)
    } else {
      index = index > 100 || !index ? '100+' : index
      prefab.getChildByPath("left/index").getComponent(Label).string = `${index}`
    }
    prefab.getChildByPath("info/name").getComponent(Label).string = item.nickname
    prefab.getChildByPath("info/score/label").getComponent(Label).string = `${item.totalScore}`
    if (item.headUrl) {
      this.handleHearUrl(prefab, item.headUrl)
    }

    if (item.totalScore) {
      this.handleAchievement(prefab, item.totalScore)
    }

    return prefab
  }

  // 更新预制体左侧UI
  handleItemLeft(prefab, index) {
    switch (index) {
      case 1:
        // console.log(this.itemLeftList[0], 'this.itemLeftList[0]111')
        prefab.getChildByName("left").getComponent(Sprite).spriteFrame = this.itemLeftList[0]
        break;
      case 2:
        prefab.getChildByName("left").getComponent(Sprite).spriteFrame = this.itemLeftList[1]
        break;
      case 3:
        prefab.getChildByName("left").getComponent(Sprite).spriteFrame = this.itemLeftList[2]
        break;
    }
  }


  // 处理微信头像
  handleHearUrl(prefab, url) {
    // 远程 url 不带图片后缀名
    assetManager.loadRemote<ImageAsset>(url, { ext: '.png' }, function (err, imageAsset) {
      const spriteFrame = new SpriteFrame();
      const texture = new Texture2D();
      texture.image = imageAsset;
      spriteFrame.texture = texture;
      // console.log(spriteFrame, 111)
      prefab.getChildByPath("info/tx-box/Mask/touxiang").getComponent(Sprite).spriteFrame = spriteFrame
    });
  }

  // 处理官职图片
  handleAchievementUrl(prefab, url) {
    // 远程 url 带图片后缀名
    assetManager.loadRemote<ImageAsset>(url, function (err, imageAsset) {
      const spriteFrame = new SpriteFrame();
      const texture = new Texture2D();
      texture.image = imageAsset;
      spriteFrame.texture = texture;
      // console.log(spriteFrame, 111)
      prefab.getChildByPath("info/tx-box/guanzhi").getComponent(Sprite).spriteFrame = spriteFrame
    });
  }

  // 处理分数对应官职
  handleAchievement(prefab, totalScore) {
    let activeUrl;
    this.imglist.forEach(element => {
      // console.log(element.score, totalScore, 111)
      if (totalScore > element.score) {
        activeUrl = element.activeUrl
      }
    })
    // console.log(activeUrl, 'activeUrl')
    if (activeUrl) {
      this.handleAchievementUrl(prefab, activeUrl)
    }
  }

}

